import random
import time

from sqlalchemy import and_

from exts import db
from flask import Blueprint, request, Response, jsonify, render_template, url_for, redirect, session
import json

from opinions.model import Opinions
from student.model import Student
from user.model import User

opinions = Blueprint('opinions', __name__);

# 意见列表
@opinions.route('opinions_list', methods=['GET', 'POST'])
def opinions_list():
    opinions_list = Opinions.query.all()
    return render_template('opinions_list.html', opinions_list=opinions_list)

# 意见搜索
@opinions.route('/opinions/search', methods=['GET', 'POST'])
def search():
    keyword = request.args.get('keyword')
    opinions_list = Opinions.query.filter(
        Opinions.opinions1.like('%{keyword}%'.format(keyword=keyword))
    ).all()
    return render_template('opinions_list.html', opinions_list=opinions_list)

# 删除意见
@opinions.route('/opinions/remove', methods=['GET', 'POST'])
def remove():
    id = request.args.get('id')
    opinions = Opinions.query.filter(
        Opinions.id == id
    ).first()
    db.session.delete(opinions)
    db.session.commit()
    return redirect(url_for('opinions.opinions_list'))

# 意见详情，编辑，更新，添加
@opinions.route('/opinions/edit', methods=['GET', 'POST'])
def edit():
    if request.method=='GET':
        id = request.args.get('id')
        option = request.args.get('option')
        opinions = Opinions.query.filter(
            Opinions.id == id
        ).first()
        if option == 'detail':
            return render_template('opinions_editor.html', opinions=opinions)
        else:
            return render_template('opinions_editor.html', opinions=opinions, update=True)
    else:
        id = request.form.get('id')
        opinions1 = request.form.get('opinions1')
        opinions2 = request.form.get('opinions2')
        opinions3 = request.form.get('opinions3')

        opinions = Opinions.query.filter(
            Opinions.id == id
        ).first()
        if opinions is None:
            opinions = Opinions(opinions1=opinions1, opinions2=opinions2, opinions3=opinions3)
            db.session.add(opinions)
            db.session.commit()
        else:
            opinions.opinions1 = opinions1
            opinions.opinions2 = opinions2
            opinions.opinions3 = opinions3
            db.session.commit()
        return redirect(url_for("opinions.opinions_list"))